package server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class TaskConnection implements Runnable{

	private final Socket socket;
	public TaskConnection(Socket sock) {
		socket = sock;
	}

	@Override public void run() {
		ObjectInputStream in = null;
		ObjectOutputStream out = null;
		try {
			in = new ObjectInputStream(socket.getInputStream());
			out = new ObjectOutputStream(socket.getOutputStream());
			String result = null;
			// Read data from socket
			String message = (String)in.readObject();
			System.out.printf("Server> New task thread launched, initial data: \"%s\"%n", message);
			
			// If it is our command, check for being in the int range
			if (message.matches("toPrimes:\\d+")){
				try {
					result = PrimeMachine.GetAsPrimes(Integer.parseInt(message.substring(9)));	
				} catch (NumberFormatException e) {
					result = "Sorry, this number is not supported in the current version. Please, try again later. \r\nNumbers currently supported are up to 2^31 - 1";
				}
			} else {
				result = "Sorry, can't understand you. You wrote:" + message;
			}
			
			// Tells results to the client
			try {
				out.writeObject(result);
				out.flush();
			} catch (Exception e) {
				result = "Can't send data back to the client, he is probably gone";
			}
			
			
			System.out.println("Server> " + result);
			
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} finally{
			try {
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

}
